<template>
  <div class="user-edit">
    <div class="edit-avatar">
      <div class="avatar">
        <img :src="avatar || defaultAvatar" alt="" />
        <el-upload
          action="zhanweifu"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="changeFile"
        >
          <span v-loading="uploadLoading"></span>
        </el-upload>
      </div>
    </div>
    <div class="edit-container">
      <el-form ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input
            v-model="editForm.nickName"
            @input="changeForm"
            placeholder="填写昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="个人介绍">
          <el-input
            v-model="editForm.introduction"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 4 }"
            @input="changeForm"
            maxlength="180"
            show-word-limit
            placeholder="填写个人介绍"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="editForm.phone"
            @input="changeForm"
            placeholder="填写手机号"
          ></el-input>
        </el-form-item>
        <el-form-item
          style="text-align: right"
          :class="{ 'fade-in': isShowForm, 'fade-out': !isShowForm }"
        >
          <el-button
            type="primary"
            @click="updateUserInfo"
            :loading="updateLoading"
            >完成</el-button
          >
        </el-form-item>
      </el-form>
      <div class="edit-pwd">
        <p>设置密码</p>
        <div class="pwd-ipt">
          <el-input
            v-model="oldPwd"
            placeholder="请输入旧密码"
            @blur="oldPwdChange"
            type="password"
          ></el-input>
          <div
            style="width: 100%"
            v-loading="checkLoading"
            element-loading-spinner="el-icon-loading"
          >
            <i class="el-icon-success" v-show="oldPwdRight"></i>
            <i class="el-icon-error" v-show="oldPwdError">密码错误</i>
          </div>
        </div>
        <div class="pwd-ipt" v-show="oldPwdRight">
          <el-input
            v-model="newPwd"
            type="password"
            @input="newPwdChange"
            placeholder="请输入新密码"
          ></el-input>
          <i class="el-icon-success" v-show="newPwdRight"></i>
          <i class="el-icon-error" v-show="newPwdError">密码不一致</i>
        </div>
        <div class="pwd-ipt" v-show="oldPwdRight">
          <el-input
            v-model="verifyNewPwd"
            type="password"
            @input="newPwdChange"
            placeholder="重新输入新密码"
          ></el-input>
          <i class="el-icon-success" v-show="newPwdRight"></i>
          <i class="el-icon-error" v-show="newPwdError">密码不一致</i>
        </div>
        <div class="pwd-btn" v-show="newPwdRight" @click="updatePwd">
          <el-button type="primary" :loading="updatePwdLoading">修改</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import defaultAvatar from "@/assets/defaultAvatar.png";
import { getUserInfo, updateUserInfo, checkPassword } from "@/api/user";
import { uploadFile } from "@/api/common";
import userInfo from "@/utils/userInfo";
export default {
  name: "UserEditView",
  data() {
    return {
      defaultAvatar,
      avatar: "",
      editForm: {},
      dataObj: {},
      oldPwd: "",
      newPwd: "",
      verifyNewPwd: "",
      isShowForm: false,
      oldPwdRight: false,
      oldPwdError: false,
      newPwdRight: false,
      newPwdError: false,
      // 加载动画
      uploadLoading: false,
      updateLoading: false,
      checkLoading: false,
      updatePwdLoading: false,
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const user = userInfo.getUser();
      if (!user) {
        this.$router.push("/login");
        return;
      }
      const res = await getUserInfo(user.userId);
      this.avatar = res.data.avatar;
      this.editForm = Object.assign(
        {},
        {
          id: res.data.id,
          nickName: res.data.nickName || "",
          introduction: res.data.introduction || "",
          phone: res.data.phone || "",
        }
      );
      this.dataObj = Object.assign(
        {},
        {
          id: res.data.id,
          nickName: res.data.nickName || "",
          introduction: res.data.introduction || "",
          phone: res.data.phone || "",
        }
      );
    },
    // 判断是否显示完成按钮
    changeForm() {
      const objectEqual =
        JSON.stringify(this.editForm) === JSON.stringify(this.dataObj);
      if (!objectEqual) {
        this.isShowForm = true;
      } else {
        this.isShowForm = false;
      }
    },
    // 提交修改
    async updateUserInfo() {
      this.updateLoading = true;
      try {
        const res = await updateUserInfo(this.editForm);
      } finally {
        this.updateLoading = false;
      }
      this.getUserInfo();
      this.isShowForm = false;
    },
    // 判断旧密码是否正确
    async oldPwdChange() {
      if (this.oldPwd === "") {
        this.oldPwdRight = false;
        this.oldPwdError = false;
        return;
      }
      this.checkLoading = true;
      const res = await checkPassword(userInfo.getUser().userId, this.oldPwd);
      this.checkLoading = false;
      if (res.data) {
        this.oldPwdRight = true;
        this.oldPwdError = false;
      } else {
        this.oldPwdRight = false;
        this.oldPwdError = true;
        this.newPwd = "";
        this.verifyNewPwd = "";
        this.newPwdRight = false;
        this.newPwdError = false;
      }
    },
    // 判断新密码是否一致
    newPwdChange() {
      if (this.verifyNewPwd === "" || this.newPwd === "") {
        this.newPwdRight = false;
        this.newPwdError = false;
        return;
      }
      if (this.newPwd === this.verifyNewPwd) {
        this.newPwdRight = true;
        this.newPwdError = false;
      } else {
        this.newPwdRight = false;
        this.newPwdError = true;
      }
    },
    // 修改密码
    async updatePwd() {
      this.updatePwdLoading = true;
      try {
        const res = await updateUserInfo({
          password: this.newPwd,
          id: userInfo.getUser().userId,
        });
      } finally {
        this.updatePwdLoading = false;
      }
      this.oldPwd = "";
      this.newPwd = "";
      this.verifyNewPwd = "";
      this.oldPwdRight = false;
      this.oldPwdError = false;
      this.newPwdRight = false;
      this.newPwdError = false;
      localStorage.removeItem("token");
      userInfo.setUser({});
      this.$router.push("/login");
      this.$message.success("重新登陆");
    },
    // 选择文件，上传封面
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const fileUrl = await uploadFile(formData);
        await updateUserInfo({
          avatar: fileUrl.data,
          id: userInfo.getUser().userId,
        });
        this.getUserInfo();
        userInfo.setUser({
          nickname: this.editForm.nickName,
          avatar: fileUrl.data,
          userId: this.editForm.id,
        });
        // 刷新页面
        this.$router.go(0);
      } finally {
        this.uploadLoading = false;
      }
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
.user-edit {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .edit-avatar {
    position: relative;
    width: 100%;
    height: 160px;
    .avatar {
      width: 100px;
      height: 100px;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        cursor: pointer;
      }
      span {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        &::before {
          content: "更换头像";
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 100px;
          height: 100px;
          background-color: rgba(0, 0, 0, 0.16);
          text-align: center;
          line-height: 100px;
          border-radius: 50%;
          cursor: pointer;
          opacity: 0;
          visibility: hidden;
          z-index: 1;
          color: black;
        }
        &:hover::before {
          opacity: 1;
          visibility: visible;
        }
      }
    }
  }
  .edit-container {
    margin: 0 auto;
    width: 70%;
    .edit-pwd {
      p {
        font-size: 15px;
        color: #999;
      }
      .pwd-ipt {
        display: flex;
        align-items: center;
        margin-top: 10px;
        margin-left: 80px;
        width: 330px;
        /deep/.el-input__inner {
          width: 200px;
        }
        i {
          width: 100%;
          height: 100%;
          margin-left: 10px;
          &:nth-of-type(1) {
            color: #67c23a;
          }
          &:nth-of-type(2) {
            color: #f56c6c;
          }
        }
      }
      .pwd-btn {
        margin-left: 146px;
        margin-top: 10px;
      }
    }
  }
  .fade-in {
    opacity: 1;
    transition: opacity 0.1s ease-in;
  }
  .fade-out {
    opacity: 0;
    transition: opacity 0.1s ease-out;
  }
}
</style>